/*
 * @Author: 冯尚新 fengshangxin@yunjinhz.com
 * @Date: 2023-05-23 10:51:51
 * @LastEditors: 冯尚新 fengshangxin@yunjinhz.com
 * @LastEditTime: 2023-05-30 21:15:07
 * @FilePath: \zmglpt-ui-mobile-v1.1\dev\common\AMapMixin.js
 * @Description: 高德地图公共代码块
 */
import AMapLoader from '@amap/amap-jsapi-loader';
import md5Libs from "@/uview-ui/libs/function/md5";
export const AMapMixin = {
  mounted() {
    // 引入高德地图
    if(!window._AMapSecurityConfig){
      window._AMapSecurityConfig = {
        securityJsCode: process.uniEnv.AMAP.SECURITY_JS_CODE,
      };
    }
    if (window.AMap) {
      this.hasInited = true;
      this.loadPlugin("AMap.Geolocation", (plg) => {
        this.initAmapOg();
        this.initAmap();
      });
    } else {
      let self = this;
      AMapLoader.load({
        "key": process.uniEnv.AMAP.JS_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": ['AMap.Geolocation',], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        "AMapUI": { // 是否加载 AMapUI，缺省不加载
          "version": '1.1', // AMapUI 缺省 1.1
          "plugins": [], // 需要加载的 AMapUI ui插件
        },
        // "Loca":{                // 是否加载 Loca， 缺省不加载
        // "version": '1.3.2'  // Loca 版本，缺省 1.3.2
        // },
      }).then(() => {
        self.hasInited = true;
        self.initAmapOg();
        self.initAmap();
      });
    }
  },
  data() {
    return {
      geolocation: undefined,
      currLocation: undefined,
      curCords: undefined,
      curPos: undefined,
      amap: undefined,
      hasInited: false,
      hasDefaultGeo:true,
    }
  },
  methods: {
    initAmapOg() {
      if(!this.hasDefaultGeo) return;
      try {
        this.geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
        });
      } catch (error) {
        console.error(error);
      }
    },
    /**
		 * 异步加载插件
		 * @param {Array/String} plugins ['AMap.ToolBar','AMap.Driving'] 或者 'AMap.ToolBar'
		 * @param {Object} callback
		 */
    loadPlugin(plugins, callback) {
      if (!window.AMap || plugins == undefined) {
        callback(false);
        return;
      }
      if (Array.isArray(plugins)) { // 多个插件
        AMap.plugin(plugins, function() { // 异步同时加载多个插件
          callback(true);
        });
      } else if (typeof plugins == 'string') { // 单个插件
        AMap.plugin(plugins, function() { // 异步加载插件
          callback(true);
        });
      } else {
        callback(false);
      }
    },
    /**
	 * 异步加载UI
	 * @param {Object} arr  ['overlay/SimpleMarker','overlay/SimpleInfoWindow']
	 * @param {Object} callback
	 * function(SimpleMarker, SimpleInfoWindow) {
		    //....引用加载的UI....
		}
	 */
    loadUI(arr, callback) {
      if (!window.AMap || arr == undefined) {
        callback();
        return;
      }
      AMapUI.loadUI(arr, callback);
    },

    /**
		 * 其他坐标转换成高德坐标
		 * var gps = [116.3, 39.9];
		 */
    covertCords(cord, type) {
      return new Promise((resolve, reject) => {
        AMap.convertFrom(cord, type, function(status, result) {
          if (result.info === 'ok') {
            resolve(result.locations[0]);
          }
        });
      });
    },
    // H5 版获取当前位置
    getCurrentLocation() {
      let self = this;
      return new Promise((resolve, reject) => {
		  self.$deviceApi.geolocation().then(geo => {
			let res = {
				lng:geo.longitude,
				lat:geo.latitude
			}
			resolve(res);
		  }).catch((err)=>{
		  	reject(err);
		  });
		  
        // self.geolocation.getCurrentPosition(function(status, result) {
        //   if (status == 'complete') {
        //     resolve(result.position);
        //   } else {
        //     reject();
        //   }
        // });
      });
    },
    // 标记当前位置
    setCurrentPointMarker() {
      // 地图中添加地图操作ToolBar插件
      this.currLocation = new AMap.Marker({
        title: "当前位置",
        // topWhenClick: true,
        // clickable: true,
        icon: new AMap.Icon({ // 复杂图标
          size: new AMap.Size(25, 25), // 图标大小
          imageSize: new AMap.Size(25, 25),
          image: "static/map/loc.png", // 大图地址
        }),
        position: this.curCords,
        label: null,
        // draggable: false, //* **修改了这里***
      });
      this.currLocation.setMap(this.amap); // 在地图上添加点
    },

    // 标记当前位置
    updateCurrentPointMarker() {
      // 地图中添加地图操作ToolBar插件
      if (this.amap != undefined) {
        if (this.currLocation != undefined) {
          this.currLocation.setPosition(this.curCords);
        } else {
          this.setCurrentPointMarker();
        }
        this.amap.setZoomAndCenter(13, this.curCords, false);
      }
    },
    // 其他公共方法
    // 测量距离
    getCurDistance(data) {
      let headers = {};
      headers['Content-Type'] = "application/json; charset=UTF-8";
	  data.key = process.uniEnv.AMAP.SERVER_KEY;
      let str = this.$u.queryParams(data,false,);
      data.sig = md5Libs.md5(`${str}${process.uniEnv.AMAP.SERVER_PRIVATE_KEY}`);
      return new Promise(function(resolve, reject) {
        uni.request({
          url: 'https://restapi.amap.com/v3/distance',
          data: data,
          header: headers,
          method: "GET", 
          success: (response) => {
            let res = response.data;
            if (res.status === "1") { // 服务端返回的状态码不等于200，则reject()
              resolve(res.results);
            } else {
              reject(res.info);
            }
          },
          fail: (err) => {
            console.log(err);
            reject('测距失败');
          },
        })
      });
    },
    // 绘制路线
    getRoutsData(data) {
      let headers = {};
      headers['Content-Type'] = "application/json; charset=UTF-8";
	  data.key = process.uniEnv.AMAP.SERVER_KEY;
      let str = this.$u.queryParams(data,false,);
      data.sig = md5Libs.md5(str + process.uniEnv.AMAP.SERVER_PRIVATE_KEY);
      return new Promise(function(resolve, reject) {
        uni.request({
          url: 'https://restapi.amap.com/v3/direction/walking',
          data: data,
          header: headers,
          method: "GET", 
          success: (response) => {
            let res = response.data;
            if (res.status === "1") { // 服务端返回的状态码不等于200，则reject()
              resolve(res.route.paths[0]);
            } else {
              reject(res.info);
            }
          },
          fail: (err) => {
            console.log(err);
            reject('未找到周围中小学信息');
          },
        })
      });
    },
    // 搜索周围中小学信息
    getAroundSchool(data){
      let headers = {};
      headers['Content-Type'] = "application/json; charset=UTF-8";
	  data.key = process.uniEnv.AMAP.SERVER_KEY;
      let str = this.$u.queryParams(data,false,);
      data.sig = md5Libs.md5(str + process.uniEnv.AMAP.SERVER_PRIVATE_KEY);
      return new Promise(function(resolve, reject) {
        uni.request({
          url: 'https://restapi.amap.com/v5/place/around',
          data: data,
          header: headers,
          method: "GET", 
          success: (response) => {
            let res = response.data;
            if (res.status === "1") { // 服务端返回的状态码不等于200，则reject()
              resolve(res.pois);
            } else {
              reject(res.info);
            }
          },
          fail: (err) => {
            console.log(err);
            reject('绘制路线失败');
          },
        })
      });
    },
  },
}
